import os
import sys
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.applications.vgg19 import preprocess_input
from keras.applications.vgg19 import decode_predictions
from keras.applications.vgg19 import VGG19
from keras.models import Model
import numpy as np
import json
import cv2
import time
from pymongo import MongoClient
import pymongo
img_path = 'E:\\image_pi_new_p2\\'

client = MongoClient(port=27017)
db=client['tiktok_p2_1']


collistt=['gaminglife', 'whatilearned', 'happyholi', 'stpatricksday', 'ontherunway', 'joblife', 'homecooked', 'tiktokcars', 'gettheretogether', 'zodiacsign', 'hellowinter', 'healthyheart', 'tiktokfood', 'petsontiktok', 'homecook', 'timewarpwaterfall', 'tiktokdiy', 'graphicdesign', 'holidaycrafts', 'foodtiktok', 'emophase', 'neontwin', 'tiktokwildlifeday', 'nflplayoffs', 'smallbusiness', 'needtoknow', 'superbowllv', 'mifamilia', 'nbaallstar', 'hyperfixated', 'couplethings', 'kissyourpet', 'greenscreenscan', 'tabletop', 'wildanimals', 'stemlife', 'easyrecipe', 'fallguysmoments', 'inkdrawing', 'gamenight', 'planttiktok', 'yellow', 'imaghost', 'mlkday', 'perfectmatch', 'homecafe', 'siblinggoals', 'whenwomenwin', 'promszn', 'halloweenlook', 'christmas2020', 'diyprojects', '2018vs2021', 'tiktokfashionmonth', 'theatrekids', 'mystyle', 'artmas', 'wrestlemania', 'cleaningtiktok', 'mypfp', 'holidaymusic', 'beautyhack', 'carsoftiktok', 'moneytok', 'homediy', 'holidaysourway', 'ratatouillemusical', 'happyhanukkah', 'colddays', 'thriftflip', 'carhacks', 'familyimpression', 'aprilfools', 'falldiy', 'recordsday', 'givingthanks', 'cartiktok', 'fallfashion', 'homeimprovement', 'crowdcheers', '2021affirmations', 'mobilegame', 'problemsolved', 'herstory', 'weirdpets', 'nbaisback', 'haventseen', 'baseballtiktok', 'ohno', 'clingypet', 'fantheory', 'coversforlovers', 'homemade', 'learnwithme', 'happyeaster', 'womeninstem', 'seashanty', 'somethingyoulearned', 'whenwewereyounger', 'vinylclub', 'productivity', 'animation', 'yearontiktok', 'coldweather', 'rareaesthetic', 'sidetable', 'onlinedating', 'puppybowl', 'perfectdrink', 'colorblast', 'sheesh', 'roomtour', 'thriftshop', 'sfxmakeup', 'housetour', 'perfectgifts', 'myrecommendation', 'nowruz', 'weekendvibes', 'givingszn', 'royalrumble', 'neonshadow', 'springvibes', 'learnontiktok', 'defrosting', 'doctorsoftiktok', 'healthycooking', 'dailyvlog', 'stylehacks', 'nhlfaceoff', 'ecohacks', 'catchphrases', 'wishlist', 'personalfinance', 'meditation101', 'diceroll', 'youwantmore', 'wordsofwisdom', 'upcycling', 'stepbystep', 'wip', 'baseballisback', 'welldone', 'onhold', 'unwrapthedeals', 'halloweenishere', 'notaperfectperson', 'typing', 'foodie', 'beautyhacks', 'inspirationalquotes', 'snowstorm', 'tipsandtricks', 'puppiesonly', 'fanedit', 'howbizarre', 'marchmadness', 'myhaul', 'meleaving', 'blackandproud', 'dayandnight', 'veteransday', 'fitnesslife', 'readysetshop', 'earthday', 'valentinesdiy', 'nonuancenovember', 'pleasedontgo', 'amongus', 'imbusyrightnow', 'naturescereal', 'holidaytiktok', 'itwasntaphase', 'winterfashion', 'melaninmagic', 'whereilive', 'laughingduet', 'winterfit', 'groupchat', 'myhobby', '90saesthetic', 'nowlookatthis', 'inlove', 'projectcar', 'relationshipstorytime', 'happyhalloween', 'yougotthis', 'galentinesday', 'welcome2021', 'motivationmonday', 'festivefashion', 'visionboard', 'comfortfood', 'givethanksnotpranks', 'fetapasta', 'horrortok', 'bekind', 'inverted', 'careeradvice', 'growupwithme', 'hellospring', 'feelinggood', 'sabiasque', 'isthisavailable', 'workingathome', 'goodmorning', 'bye2020', 'athletesoftiktok', 'takeabite', 'easydiy', 'watchmegrow', 'holidaydecor', 'seitan', 'myroutine', 'foodontiktok', 'holidaytreats', 'dinnerparty', 'gamergoals', 'tiktokfitness', 'vaccinatedfor', 'wintersports', 'sheearnedit', 'transvisibilityday', 'familyrecipe', 'cozyathome', 'gamingtiktok', 'raisedby', 'thankstoher', 'thinkingabout', 'healthyliving', 'plantparent', 'hereforrmhc', 'oscars', 'valentinesday', 'makeitvogue', 'lifestyle', 'happyholidays', 'lunarnewyear', 'olympicscountdown', 'bakingszn', 'competitivegaming', 'timewarpjump', 'homeproject', 'ourtype', 'cleantok', 'fitnessroutine', 'glasspainting', 'holidayvibes', 'blackcreatives', 'makeblackhistory', 'nativefamily', 'nbadraft', 'lovestory', 'dramaticmoments', 'tortillatrend', 'bakedoats', 'winterbeautytips', 'interiordesign', 'lookbook', 'holidaycountdown', 'ootd', 'selfimprovement', 'albumcover', 'passover', 'homebusiness', 'guitartok', 'tiktoktailgate', 'mycostume', 'science101', 'gamingsetup', 'homeoffice', 'springoutfit', 'rnbvibes', 'autismawareness', 'roundofapplause', 'passingthephone', 'tiktoktutorial', 'thrifting', 'songfacts', 'loveyourinsecurities', 'skincare101']
for hname in collistt:
    namepi=hname
    collist=[hname]
    videolist = {}
    i = 0
    for col in collist:
        videolist[col]=[]
        for item in db[col].find():
            videolist[col].append(item['_id'])
    for key in videolist.keys():
        print(key,len(videolist[key]))
    c=0
    os.system('mp4box -hint')
    for hashtag in videolist.keys():
        for vid in videolist[hashtag]:
            c+=1
            # if not os.path.exists('E:\\tiktok_new\\video\\' + hashtag + '\\' + vid + '.mp4'):
            #     continue
            vname=vid

            vidcap = cv2.VideoCapture('E:\\tiktok_new\\video\\' + hashtag + '\\' + vid + '.mp4')
            frame_count = vidcap.get(cv2.CAP_PROP_FRAME_COUNT)
            fps = vidcap.get(cv2.CAP_PROP_FPS)
            fl =frame_count/10/fps
            init=fl/2
            count = 0
            vidcap.set(cv2.CAP_PROP_POS_MSEC, (round((init+count * fl)*1000)))
            success, image = vidcap.read()

            while success:

                if os.path.exists(img_path + vname + "_%d.jpg" % count+'.jpg'):
                    count+=1
                    continue
                cv2.imwrite(img_path + vname + "_%d.jpg" % count, image[round(len(image)/10):round(len(image)-len(image)/10)])
                count = count + 1
                vidcap.set(cv2.CAP_PROP_POS_MSEC, round((init + count * fl) * 1000))
                success, image = vidcap.read()

                if count>9:
                    break
    idlist=[]
    for ht in videolist.keys():
        idlist.extend(videolist[ht])
    with open('E:\\data_pi\\imglist_temp'+namepi+'_new_p2.txt','w') as file_input:
        c=0
        for vname in os.listdir(img_path):
            v=vname.split('_')[0]
            if vname.endswith('.jpg') and v in idlist:
                c+=1
                file_input.write(img_path+vname+'\n')
        print(c)
    os.system('"'+'py -2 D:\\Work\\kusuri\\DeepSentiBank\\sentiBank.py '+'E:\\data_pi\\imglist_temp'+namepi+'_new_p2.txt'+'"')


    base_model = VGG19(weights='imagenet')
    model = Model(base_model.input, base_model.get_layer('fc2').output)
    col=''
    with open ('E:\\data_pi\\imglist_temp'+namepi+'_new_p2.txt','r',) as txt_input:
        with open ('E:\\data_pi\\imglist_temp'+namepi+'_new_p2.json','r',) as json_input:
            senti=json.load(json_input)
            c=0
            prev=''
            l=0
            avg=[]
            for line in txt_input:
                line=line.replace(img_path,'')
                print(line,c)
                iid=line.split('_')[0]
                imgnum=line.split('_')[1].replace('.jpg','').strip()
                for ht in videolist.keys():
                    if iid in videolist[ht]:
                        col=ht
                        break
                ori = db[col].find_one({'_id': iid})
                if len(ori['frame_level']['f'+imgnum]['img'])>0:
                    c+=1
                    continue
                print(iid)
                tempresult=[]
                line=line.strip()
                img = load_img(img_path+line,target_size=(224, 224))
                img = img_to_array(img)
                img = np.expand_dims(img, axis=0)
                img = preprocess_input(img)
                fc2_features = model.predict(img)
                prob_vgg = decode_predictions(base_model.predict(img), top=1000)
                for item in sorted(prob_vgg[0]):
                    tempresult.append(float(item[2]))
                for item in sorted(senti['images'][c]['bi-concepts']):
                    tempresult.append(float(senti['images'][c]['bi-concepts'][item]))
                for item in senti['images'][c]['features']:
                    tempresult.append(float(item))
                for ht in videolist.keys():
                    if iid in videolist[ht]:
                        col=ht
                        break
                db[col].update_one({'_id': iid}, {'$set':{'frame_level.f'+imgnum+'.img':tempresult}})
                print(db[col].find_one({'_id': iid}))
                c+=1
